package com.company.controller;

import com.company.mapper.UserMapper;
import com.company.model.User;
import com.company.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8"); // 新增：处理中文乱码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 非空校验（新增：防止空指针）
        if (username == null || username.trim().isEmpty()
                || password == null || password.trim().isEmpty()) {
            request.setAttribute("error", "用户名或密码不能为空");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }

        SqlSession session = null;
        try {
            session = MyBatisUtil.getSqlSession();
            UserMapper userMapper = session.getMapper(UserMapper.class);
            User user = userMapper.login(username, password); // 调用MyBatis查询

            if (user != null) {
                HttpSession httpSession = request.getSession();
                httpSession.setAttribute("user", user); // 存储登录状态
                response.sendRedirect(request.getContextPath() + "/employee/list");
            } else {
                request.setAttribute("error", "用户名或密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }
        } catch (Exception e) {
            // 新增：捕获MyBatis初始化异常，提示用户
            e.printStackTrace();
            request.setAttribute("error", "系统错误，请联系管理员");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        } finally {
            if (session != null) {
                MyBatisUtil.closeSqlSession(session); // 确保资源关闭
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}